package com.rskj.cashbook.task;

import com.rskj.cashbook.service.ISqlMonitorLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class SqlMonitorCleanupTask {

    @Autowired
    private ISqlMonitorLogService sqlMonitorLogService;

    @Value("${sql.monitor.cleanup.enabled:true}")
    private boolean cleanupEnabled;

    @Value("${sql.monitor.retention-days:30}")
    private Integer retentionDays;

    /**
     * 每天凌晨2点执行清理任务
     */
    @Scheduled(cron = "${sql.monitor.cleanup.cron:0 0 2 * * ?}")
    public void cleanupExpiredLogs() {
        if (!cleanupEnabled) {
            log.debug("SQL监控日志清理任务已禁用");
            return;
        }

        try {
            log.info("开始执行SQL监控日志清理任务");
            
            LocalDateTime expireTime = LocalDateTime.now().minusDays(retentionDays);
            int deletedCount = sqlMonitorLogService.cleanExpiredLogs(expireTime);
            
            log.info("SQL监控日志清理任务完成，删除记录数: {}", deletedCount);
        } catch (Exception e) {
            log.error("SQL监控日志清理任务执行失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 每小时执行一次统计任务
     */
    @Scheduled(cron = "${sql.monitor.statistics.cron:0 0 * * * ?}")
    public void generateStatistics() {
        if (!cleanupEnabled) {
            return;
        }

        try {
            log.debug("开始生成SQL监控统计信息");
            
            LocalDateTime startTime = LocalDateTime.now().minusHours(1);
            var statistics = sqlMonitorLogService.getSqlStatistics(startTime);
            
            if (!statistics.isEmpty()) {
                log.info("SQL监控统计信息 - 总执行数: {}, 成功数: {}, 失败数: {}, 平均耗时: {}ms", 
                        statistics.get("totalCount"),
                        statistics.get("successCount"),
                        statistics.get("failedCount"),
                        statistics.get("avgDuration"));
            }
        } catch (Exception e) {
            log.error("生成SQL监控统计信息失败: {}", e.getMessage(), e);
        }
    }
}

